using GameFramework.Event;
using GameFramework.Fsm;
using GameFramework.Procedure;
using LS.Saving;

namespace LS.Procedure
{
    public class ProcedurePreloadSaving : ProcedurePreloaderBase
    {
        public override bool UseNativeDialog => false;

        public override int PreloadPriority => 16;

        private bool m_LoadFinish = false;

        protected override void OnEnter(IFsm<IProcedureManager> procedureOwner)
        {
            base.OnEnter(procedureOwner);
            var saving = LSEntry.Saving;
            LSEntry.Event.Subscribe(LoadDatabaseSuccessEventArgs.EventId, OnLoadSuccess);
            LSEntry.Event.Subscribe(LoadDatabaseFailureEventArgs.EventId, OnLoadFailure);
            StartLoadSaving();
        }

        protected override void OnUpdate(IFsm<IProcedureManager> procedureOwner, float elapseSeconds, float realElapseSeconds)
        {
            base.OnUpdate(procedureOwner, elapseSeconds, realElapseSeconds);
            if (!m_LoadFinish)
            {
                return;
            }

            ChangeNextProcedure(GetNextProcedureType());
        }

        protected override void OnLeave(IFsm<IProcedureManager> procedureOwner, bool isShutdown)
        {
            LSEntry.Event.Unsubscribe(LoadDatabaseSuccessEventArgs.EventId, OnLoadSuccess);
            LSEntry.Event.Unsubscribe(LoadDatabaseFailureEventArgs.EventId, OnLoadFailure);
            base.OnLeave(procedureOwner, isShutdown);
        }

        private void StartLoadSaving()
        {
            var saving = LSEntry.Saving;
            if (saving == null)
            {
                m_LoadFinish = true;
                return;
            }

            string defaultGroupName = "Default";
            if (saving.HasSavingGroup(defaultGroupName))
            {
                IDataFile file = saving.GetRecentlyFile(defaultGroupName);
                if (file == null)
                {
                    m_LoadFinish = true;
                    return;
                }
                saving.Load(defaultGroupName);
            }
        }

        private void OnLoadSuccess(object sender, GameEventArgs args)
        {
            LoadDatabaseSuccessEventArgs arg = args as LoadDatabaseSuccessEventArgs;
            if (arg == null) return;

            if (arg.GroupName == "Default")
            {
                m_LoadFinish = true;
            }
        }
        
        private void OnLoadFailure(object sender, GameEventArgs args)
        {
            LoadDatabaseFailureEventArgs arg = args as LoadDatabaseFailureEventArgs;
            if (arg == null) return;

            if (arg.GroupName == "Default")
            {
                m_LoadFinish = true;
            }
        }
    }
}
